<?php
/**
 * @Author: rocky
 * @Copyright: 广州拓冠科技 <http://my8m.com>
 * Date: 2019/8/28
 * Time: 17:54
 */


namespace app\shop\controller\api\v1;



use app\common\controller\BaseApiController;
use app\common\facade\Token;
use app\shop\model\ShopCart;
use app\shop\model\ShopGoodsSpec;
use app\shop\resource\CartResoure;
use app\shop\validate\CartValidate;

/**
 * 购物车
 * Class Cart
 * @package app\shop\controller\api\v1
 */
class Cart extends BaseApiController
{
    //获取购物车列表
    public function getInfo(){
        $data = ShopCart::uid()->pages()->with(['goods.specs','spec'])->select();
        $this->successCode(CartResoure::collection($data));
    }
    //添加商品到购物车
    public function postInfo()
    {
        $data = (new CartValidate())->goCheck();
        $where['good_id'] = $data['good_id'];
        $where['spec_id'] = $data['spec_id'];
        $cart = ShopCart::uid()->where($where)->find();
        $stock_num = ShopGoodsSpec::where('id', $data['spec_id'])->value('stock');
        if($stock_num <  $data['num']){
            $this->errorCode(5006);
        }
        if ($cart) {
            $cart->setInc('num', $data['num']);
        } else {
            $data['uid'] = Token::id();
            ShopCart::create($data);
        }
        $this->successCode();
    }
    //购车修改
    public function putInfo()
    {
        $id = $this->request->param('cart_id');
        $num = $this->request->param('num');
        $cart = ShopCart::find($id);
        $stock_num = ShopGoodsSpec::where('id', $cart['spec_id'])->value('stock');
        if($stock_num < $num){
            $this->errorCode(5006);
        }
        ShopCart::uid()->where('id', $id)->update([
            'num' => $num,
        ]);
        $this->successCode();
    }
    //删除
    public function deleteInfo(){
        $id = $this->request->param('cart_id');
        ShopCart::uid()->where('id', $id)->delete();
        $this->successCode();
    }
}